package main

import (
	"bytes"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"syscall"
)

type FileLoader struct {
}

func (h *FileLoader) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	requestedFilename := strings.TrimPrefix(req.URL.Path, "/")
	if strings.EqualFold(requestedFilename, "list.html") {
		ss, _ := getDevices()
		buf := new(bytes.Buffer)
		err := listTpl.Execute(buf, map[string]any{"Data": ss})
		if err != nil {
			res.WriteHeader(http.StatusBadRequest)
			_, _ = res.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename)))
			return
		}
		fmt.Println(buf.String())
		_, _ = res.Write(buf.Bytes())
		return

	}
	var err error
	println("Requesting file:", requestedFilename)
	fileData, err := os.ReadFile(requestedFilename)
	if err != nil {
		res.WriteHeader(http.StatusBadRequest)
		res.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename)))
	}
	_, _ = res.Write(fileData)
}

func getDevices() ([]string, error) {
	var cmd = exec.Command("./scrcpy/adb.exe", "devices")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		HideWindow:    true,
		CreationFlags: 0x08000000,
	}
	bs, err := cmd.CombinedOutput()
	if err != nil {
		return nil, err
	}
	str := string(bs)
	fmt.Println(str)
	var stars = strings.Split(str, "\n")
	var res []string
	for _, s := range stars[1:] {
		sss := strings.Fields(s)
		if (len(sss)) == 0 {
			continue
		}
		res = append(res, sss[0])
	}
	return res, nil
}

func getFirstDevice() (string, error) {
	var cmd = exec.Command("./scrcpy/adb.exe", "devices")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		HideWindow:    true,
		CreationFlags: 0x08000000,
	}
	bs, err := cmd.CombinedOutput()
	if err != nil {
		return "", err
	}
	str := string(bs)
	var stars = strings.Split(str, "\n")
	var res = make([]string, len(stars)-1)
	if len(res) == 0 {
		return "", errors.New("找不到设备")
	}
	for index, s := range stars[1:] {
		sss := strings.Fields(s)
		if (len(sss)) == 0 {
			continue
		}
		res[index] = sss[0]
	}
	return res[0], nil
}

func getMyDevice() (string, error) {
	return getFirstDevice()
}
